<template>
    <view class="shopping-cart-box">
        <template v-if="shopList?.length > 0">
            <checkbox-group 
                class="my-checkbox-group"
                @change="checkbox1Change"
            >
                <view
                    v-for="(item, index) in shopList"
                    :key="index"
                    class="shopping-cart-main"
                >
                    <label>
                        <checkbox 
                            :value="index" 
                            :checked="item.status=='selected'"
                        />
                    </label>
                    <image
                        :src="CONSTANT_URL.TY+item.coverImageUrl?.split(',')[0]" 
                        :draggable="false"
                        mode="scaleToFill"
                        class="shopping-cart-main-img"
                    ></image>
                    <view class="shopping-cart-main-text">
                        <view class="shopping-cart-main-text-1">{{ item.productName }}</view>
                        <view class="shopping-cart-main-text-2">{{ item.skuName }}</view>
                        <view class="shopping-cart-main-text-3">
                            <view class="shopping-cart-main-text-3-right">
                                ￥{{ Number(item.price).toFixed(2) }}
                            </view>
                            <uni-number-box
                                v-model="item.quantity"
                                :min="1"
                                @change="quantityChange(item)"
                            ></uni-number-box>
                        </view>
                        
                    </view>
                </view>
            </checkbox-group>
            <view class="shopping-cart-footer">
                <view class="shopping-cart-footer-1">
                    <checkbox-group
                        class="my-checkbox2-group"
                        @change="checkbox2Change"
                    >
                        <checkbox :checked="isAllChecked" />
                    </checkbox-group>
                    <view>全选</view>
                </view>
                <view class="shopping-cart-footer-2">
                    <view class="shopping-cart-footer-2-text">合计：￥{{  Number(moneyCount).toFixed(2) }}</view>
                    <button
                        type="warn"
                        :class="['shopping-cart-button-1']"
                        style=""
                        @click="del" 
                    >
                        删除
                    </button>
                    <button
                        :class="['shopping-cart-button-2']"
                        style=""
                        @click="onSubmit" 
                        
                    >
                        去结算({{ moneyLen }})
                    </button>
                </view>
            </view>
        </template>
        <template v-else>
            <view class="shopping-cart-empty">
                <image
                    src="https://suyuan-axt.tianxunwang.com:10098/assets/suyuan-axt/portal/empty-box.png" 
                    :draggable="false"
                    mode="scaleToFill"
                    class="shopping-cart-empty-img"
                ></image>
                <view class="shopping-cart-empty-text">
                    您的购物车空空如也
                </view>
                <button
                    :class="['shopping-cart-empty-button']"
                    style=""
                    @click="goMall" 
                >
                    去逛逛
                </button>
            </view>
        </template>
    </view>
</template>

<script lang="ts" setup>
    import { onLoad, onShow, onHide, onReady, onUnload, onPullDownRefresh, onReachBottom } from '@dcloudio/uni-app'
    import { markRaw, reactive, ref } from 'vue'
    import type { Ref, Raw } from 'vue'
    import { isPhone } from '@/utils/utils'
    import { getCartApi, putCartApi,deleteCartApi,postCartIdSelectApi,postCartIdUnselectApi,postCartSelectApi,postCartUnselectApi } from '@/apis'
    import { CONSTANT_URL } from '@/apis/constant.ts'
    const popup1: Ref<any> = ref(null)
    const address: Ref<string> = ref('')
    const formData: Ref<any> = ref({})
    const isAllChecked: Ref<boolean> = ref(false)
    const moneyCount: Ref<number> = ref(0)
    const moneyLen: Ref<number> = ref(0)
    const shopList: Ref<any[]> = ref([
    ])
    onLoad((val: any) => {
      
    })
    onShow(() => {
       if ((!uni.getStorageSync('token'))) {
           let pages = getCurrentPages()
           let url = pages[pages.length - 1].route
           uni.reLaunch({
               url: "/pages/login/login?url=/" + url
           })
       }else{
           getCartApi({
               userId : uni.getStorageSync('userId')
           }).then((res: any)=> {
               shopList.value = res.data
           })
       }
       
    })
    
    const quantityChange = (val: any) => {
        console.log(val)
        moneyCount.value = 0
        moneyLen.value = 0
        shopList.value.forEach((item, index) => {
            if (item.status == 'selected') {
                moneyCount.value += item.price * item.quantity
                moneyLen.value += item.quantity
            }
        })
        // 更新购物车数据
        putCartApi(val.id,{
            id: val.id,
            userId: val.userId,
            productSkuId: val.productSkuId,
            quantity: val.quantity,
        })
    }
    
    const onSubmit = () => {
        if (moneyLen.value > 0) {
            let arr1: any = []
            let arr2: any = []
            shopList.value.forEach((item, index) => {
                if (item.status == 'unselected') {
                    arr1.push(item)
                } else {
                    arr2.push(item)
                }
            })
            // shopList.value = arr1
            // uni.setStorageSync('shopingCartArr', JSON.stringify(shopList.value))
            uni.setStorageSync('commoditiesClearingArr', JSON.stringify(arr2))
            
            // isAllChecked.value = false
            // moneyLen.value = 0
            // moneyCount.value = 0
            
            uni.navigateTo({
                url: '/pages/commoditiesClearing/commoditiesClearing'
            })
        } else {
            uni.showToast({
                title: '请选择商品！',
                icon: 'error',
                duration: 1500,
                mask: true,
            });
        }
        
    }
    const checkbox1Change = (e: any) => {
        console.log(e)
        if (e.detail.value.length == shopList.value.length && e.detail.value.length > 0) {
            isAllChecked.value = true
        } else {
            isAllChecked.value = false
        }
        shopList.value.forEach((item, index) => {
            item.status = 'unselected'
        })
        moneyCount.value = 0
        moneyLen.value = 0
        e.detail.value.forEach((item: any, index) => {
            console.log(item)
            shopList.value[Number(item)].status = 'selected'
            moneyCount.value += shopList.value[Number(item)].price * shopList.value[Number(item)].quantity
            moneyLen.value += shopList.value[Number(item)].quantity
        })
        shopList.value.forEach((item, index) => {
            if (item.status == 'selected') {
                postCartIdSelectApi(item.id)
            } else {
                postCartIdUnselectApi(item.id)
            }
        })
    }
    const checkbox2Change = (e: any) => {
        console.log(e)
        moneyLen.value = 0
        moneyCount.value = 0
        if (e.detail.value.length > 0) {
            isAllChecked.value = true
            shopList.value.forEach((item, index) => {
                item.status = 'selected'
                moneyCount.value += item.price * item.quantity
                moneyLen.value += item.quantity
            })
            console.log(shopList.value)
            postCartSelectApi()
        } else {
            isAllChecked.value = false
            shopList.value.forEach((item, index) => {
                item.status = 'unselected'
            })
            postCartUnselectApi()
        }
    }
    const del = () => {
        uni.showModal({
            showCancel: true,
            title: '温馨提示',
            content: '是否确定删除？',
            success: function (res3) {
                // 调接口
                
                let arr1: any[] = []
                let arr2: any[] = []
                console.log(shopList.value)
                shopList.value.forEach((item, index) => {
                    if (item.status == 'unselected') {
                        arr1.push(item)
                    } else {
                        arr2.push(item.id)
                    }
                })
                shopList.value = arr1
                // uni.setStorageSync('shopingCartArr', JSON.stringify(shopList.value))
                isAllChecked.value = false
                moneyLen.value = 0
                moneyCount.value = 0
                deleteCartApi(arr2)
                console.log(arr1)
                
                // uni.switchTab({
                // 	url: '/pages/mallOrders/mallOrders'
                // });
                // if (res3.confirm) {
                // 	console.log('用户点击确定');
                // } else if (res3.cancel) {
                // 	console.log('用户点击取消');
                // }
            }
        });
    }
    const goMall = () => {
        uni.switchTab({
            url: '/pages/mall/mall'
        })
    }
</script>

<style lang="scss" scoped>
    .shopping-cart-box {
        background: #f2f2f2;
        // width: 600rpx; 
        box-sizing: border-box; 
        // padding: 0 0 30rpx 0; 
        // border-radius: 50rpx 50rpx 0rpx 0rpx;
        height: calc(100vh - var(--window-top) - var(--window-bottom)); //var(--window-top) 页面的内容区域距离顶部距离 var(--window-bottom) 页面的内容区域距离底部距离 app不存在，h5有这两个高度
        display: flex;
        flex-direction: column;
        .my-checkbox-group {
            flex: 1;
            overflow: scroll;
        }
        .shopping-cart-header {
            display: flex;
            // justify-content: space-between;
            align-items: center;
            height: 100rpx;
            background: #fff;
            .shopping-cart-header-main {
                flex: 1;
                padding: 0 10rpx;
                font-size: 26rpx
            }
            .shopping-cart-header-icon-img {
                width: 50rpx;
                height: 50rpx
            }
            
        }
        .shopping-cart-main {
            margin-top: 10rpx; 
            background: #fff;
            display: flex;
            align-items: center;
            box-sizing: border-box;
            padding: 20rpx;
            .shopping-cart-main-img {
                width: 180rpx;
                height: 180rpx
            }
            .shopping-cart-main-text {
                height: 180rpx;
                flex: 1;
                display: flex;
                flex-direction: column;
                justify-content: space-between;
                align-items: flex-start;
                box-sizing: border-box;
                padding-left: 10rpx;
                font-size: 28rpx;
                .shopping-cart-main-text-1 {
                    // height: 85rpx;
                    height: 80rpx;
                    overflow: hidden;
                }
                .shopping-cart-main-text-2 {
                    // width: 300rpx;
                    box-sizing: border-box;
                    text-align: center;
                    padding: 8rpx;
                    // background: #dae4f2;
                    font-size: 20rpx;
                    color: rgb(134, 134, 134);
                    background: #f3f1f1;
                }
                .shopping-cart-main-text-3 {
                    width: 100%;
                    display: flex;
                    justify-content: space-between;
                    align-items: flex-end;
                    .shopping-cart-main-text-3-right {
                       // text-align: right;
                       color: #f2403c;
                       // font-weight: bold;
                       // padding-left: 10rpx;
                    }
                }
            }
        }
        .shopping-cart-footer {
            background-color: #fff;
            // height: 100rpx;
            display: flex;
            align-items: center;
            box-sizing: border-box;
            padding: 10rpx;
            // box-shadow: 0 0px 5px 1px #929292;
            // border-top: 1px solid #efeaea;
            .shopping-cart-footer-1 {
                display: flex;
                align-items: center;
                padding-left: 10rpx;
                color: rgb(153, 153, 153);
                height: 100%;
                font-size: 28rpx;
            }
            .shopping-cart-footer-2 {
                display: flex;
                justify-content: flex-end;
                align-items: center;
                flex: 1;
                .shopping-cart-footer-2-text {
                    // width: 220rpx;
                    padding-right: 20rpx;
                    font-size: 28rpx;
                }
            }
            .shopping-cart-button-1 {
                border-radius: 10rpx 0 0 10rpx;
                margin: 0;
                font-size: 28rpx;
                padding-top: 10rpx;
                padding-bottom: 10rpx;
            }
            .shopping-cart-button-2 {
                background-color: #2979ff !important;
                color: #fff !important;
                margin: 0;
                border-radius: 0 10rpx 10rpx 0;
                font-size: 28rpx;
                padding-top: 10rpx;
                padding-bottom: 10rpx;
            }
        }
        .shopping-cart-empty {
            display: flex;
            flex-direction: column;
            align-items: center;
            margin-top: 200rpx;
        }
        .shopping-cart-empty-img {
            width: 400rpx;
            height: 400rpx
        }
        .shopping-cart-empty-text {
            padding: 20rpx 0;
            color: rgb(153, 153, 153);
        }
        .shopping-cart-empty-button {
            background-color: #c83b45 !important;
            color: #fff !important;
            margin: 0;
            border-radius: 10rpx;
            font-size: 28rpx;
        }
    }
</style>
